
<template>
  <div>
    <el-form ref="ruleForms" :model="ruleForms" :rules="rules">
      <el-table
        ref="table"
        :data="ruleForms.temp"
        style="width: 100%"
        max-height="500"
        :highlight-current-row="true"
      >
        <el-table-column
          :key="Math.random()"
          prop="date"
          label="文件编号"
          min-width="220"
        >
          <template slot-scope="scope">
            <el-form-item
              :prop="'temp.' + scope.$index + '.documentCode'"
              :rules="rules.documentCode"
            >
              <el-input
                v-model.trim="scope.row.documentCode"
                :disabled="flowStatus > 1"
                @change="findDocumentData($event, scope.$index)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          :key="Math.random()"
          prop="date"
          label="文件名称"
          min-width="200"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-form-item>
              <el-input
                v-model.trim="scope.row.documentName"
                :disabled="true"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          :key="Math.random()"
          width="160"
          prop="content"
          label="文件等级"
        >
          <template slot-scope="scope">
            <!-- :prop="'temp.' + scope.$index + '.documentLevel '" -->
            <el-form-item :rules="rules.documentLevel">
              <el-select
                v-model="scope.row.documentLevel"
                :disabled="true"
                @change="handleLevelChange($event, scope.$index)"
              >
                <el-option
                  v-for="item in levels"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          :key="Math.random()"
          width="160"
          prop="content"
          label="文件属性"
        >
          <template slot-scope="scope">
            <el-form-item
              :prop="'temp.' + scope.$index + '.documentProperty'"
              :rules="rules.documentProperty"
            >
              <el-select
                v-model="scope.row.documentProperty"
                :disabled="true"
                @change="handlePropertyChange($event, scope.$index)"
              >
                <el-option
                  v-for="item in categories[scope.$index]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column
          v-if="flowStatus < 3"
          :key="Math.random()"
          prop="content"
          label="版本号"
          width="150"
        >
          <template slot-scope="scope">
            <el-form-item class="form-select">
              <el-select
                v-model="scope.row.v3"
                disabled
                placeholder="A"
                style="width: 60px"
              >
                <!-- <el-option
                  v-for="item in v1Options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                /> -->
              </el-select>
              <el-input-number
                v-model="scope.row.v4"
                disabled
                :min="0"
                :max="9"
                controls-position="right"
                style="width: 80px"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :key="Math.random()" prop="date" label="来源信息">
          <template slot-scope="scope">
            <el-form-item>
              <el-input
                v-model.trim="scope.row.sourceInfo"
                :disabled="flowStatus > 1"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          :key="Math.random()"
          fixed="right"
          label="操作"
          width="200px"
        >
          <template slot-scope="scope">
            <el-form-item>
              <!-- 删除 -->
              <el-button
                v-if="flowStatus == 1"
                class="my-but"
                @click.native="Delete_information(scope.$index, scope.row)"
                ><i class="el-icon-remove-outline" />
              </el-button>
              <!-- 查看 -->
              <el-tooltip effect="dark" content="查看文件" placement="top">
                <el-button
                  v-if="flowStatus == 2 || flowStatus == 3"
                  size="mini"
                  circle
                  @click.native="openDocument('view', scope.row)"
                  ><i class="el-icon-view" />
                </el-button>
              </el-tooltip>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div class="my-but-box">
      <el-button v-if="flowStatus == 1" class="my-but" @click="addTable"
        ><i class="el-icon-circle-plus-outline" />
      </el-button>
    </div>
  </div>
</template>

<script>
import { listDictTreeItem } from '@/api/base/dict'
import { listUserGroupAll } from '@/api/uc/userGroup'
import { copy, generateCode, getDocumentByCode } from '@/api/fd/document'
import { getFlowExist } from '@/api/xd/documentFlow'

export default {
  components: {},
  props: ['TabelBoxData'],
  data() {
    return {
      tempForms: {},
      rules: {
        documentLevel: [
          { required: true, message: '必填字段', trigger: 'change' }
        ],
        documentProperty: [
          { required: true, message: '必填字段', trigger: 'change' }
        ],
        documentName: [
          { required: true, message: '必填字段', trigger: 'blur' }
        ],
        documentCode: [
          { required: true, message: '必填字段', trigger: 'blur' }
        ],
        documentVersion: [
          { required: true, message: '必填字段', trigger: 'blur' }
        ],
        reason: [{ required: true, message: '必填字段', trigger: 'blur' }],
        modeDocumentName: [
          { required: true, message: '请上传文件', trigger: 'blur' }
        ]
      },
      ruleForms: {
        temp: [
          {
            documentName: null,
            documentCode: null,
            documentLevel: null,
            documentProperty: null,
            documentVersion: 'A0',
            sourceInfo: null,
            documentId: null,
            type: '',
            v3: '',
            v4: ''
          }
        ]
      },

      DocumentVersionData: '',
      flowStatus: '',
      levels: [],
      categories: [],
      roles: null,
      userGroup: [],
      UploadingFileData: {},
      SelectFileData: {},
      TYPE: 0
    }
  },
  computed: {
    // computedDocumentCode()=>{}
  },
  watch: {
    TabelBoxData(data) {
      this.flowStatus = data.flowStatus
      this.TYPE = data.type
      this.roles = data.roles
      if (data.temp.length > 0) {
        const newData = Array.from(data.temp) || []
        newData.forEach((e) => {
          e.previousDocumentId = e.documentId
        })
        this.ruleForms.temp = newData || []
      }
      this.loadLevelOptions()
    },
    'ruleForms.temp'(data) {
      console.log(data, '324344')
    },
    deep: true
  },
  mounted() {
    this.TYPE = this.TabelBoxData.type
  },
  methods: {
    // 添加
    addTable() {
      this.ruleForms.temp.push({
        documentName: null,
        documentLevel: null,
        documentProperty: null,
        documentVersion: 'A0',
        documentCode: null,
        sourceInfo: null,
        documentId: null,
        type: '',
        v3: '',
        v4: ''
      })
    },
    inputData(val, index) {
      if (val) {
        this.ruleForms.temp[index].documentVersion = val || 'A0'
      }
    },
    Delete_information(index, row) {
      this.$confirm('此操作将删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.ruleForms.temp.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleLevelChange(val, index) {
      for (let i = 0, len = this.levels.length; i < len; i++) {
        if (this.levels[i].value === val) {
          this.categories[index] = this.levels[i].children
          if (this.ruleForms.temp[index].documentProperty) {
            this.ruleForms.temp[index].documentProperty = ''
          }
        }
      }
    },
    handlePropertyChange(val, index) {
      const type = this.ruleForms.temp[index].documentLevel === 1 ? '1' : '0'
      generateCode({
        code: val,
        showLength: 3,
        type: Number(type)
      }).then((res) => {
        this.ruleForms.temp[index].documentCode = res.data.code
      })
    },
    loadLevelOptions() {
      listDictTreeItem({ dictGroupCode: 'document_category' }).then((res) => {
        const array = res.data
        if (array) {
          if (this.roles) {
            if (this.roles.indexOf('qa') === -1) {
              for (let i = 0, len = array.length; i < len; i++) {
                if (array[i].value === '1') {
                  array.splice(i, 1)
                  break
                }
              }
            }
          }
        }
        this.levels = array
      })
    },
    async backTempData() {
      try {
        const valid = await this.$refs.ruleForms.validate().catch((err) => {
          return err
        })
        const data = { valid: valid, documentFlowInfoList: this.ruleForms.temp }
        return data
      } catch (err) {}
    },
    openDialog(val, row, index) {
      if (val === 0) {
        this.openDialogType = '1'
        this.UploadingFileData = {
          deleteDialog: true,
          value: '',
          documentCode: row.documentCode,
          index: index
        }
        return
      } else {
        this.openDialogType = '2'
        this.SelectFileData = {
          deleteDialog: true,
          row: row,
          index: index
        }
      }
      this.getUserGroup()
      // this.dialogDocument = true
    },
    getUserGroup() {
      // 获取部门
      listUserGroupAll({ type: 0 }).then((res) => {
        res.data.forEach((item) => {
          if (item.type == 1) {
            var data = {
              value: item.userGroupId,
              label: item.userGroupName
            }
            this.userGroup.push(data)
          }
          if (item.type == 2) {
            var data = {
              value: item.userGroupId,
              label: item.userGroupName
            }
            this.userGroup.push(data)
          }
        })
      })
    },
    openDocument(val, row) {
      if (row.fileExtension.indexOf('.pdf') != -1) {
        window.open(
          process.env.VUE_APP_BASE_API +
            '/api/fd/pdf/get_document_by_pdf?documentId=' +
            row.previousDocumentId
        )
      } else {
        window.open(
          'onlyoffice/createDocument.html?&token=' +
            this.$store.getters.token +
            '&documentId=' +
            row.previousDocumentId +
            '&mode=' +
            val +
            '&urldata=' +
            process.env.VUE_APP_BASE_API
        )
      }
    },
    async findDocumentData(val, index) {
      clearTimeout(this.timeout)
      let isNext = false
      this.timeout = setTimeout(async () => {
        await getFlowExist({ documentCode: val, flowType: 2 }).then((res) => {
          if (this.TYPE === 1) {
            if (res.data === 2) {
              isNext = true
              this.$message.error('此流程已经存在')
            }
          } else if (res.data === 3) {
            isNext = true
            this.$message.error('该编号不存在现行文件')
          } else {
            isNext = false
          }
        })
        if (!isNext) {
          await getDocumentByCode({ code: val }).then((res) => {
            const { data } = Object.assign(res)
            this.ruleForms.temp[index] = data
            const newObj = {
              documentName: data.documentName,
              documentCode: data.documentCode,
              documentId: data.documentId,
              documentLevel: data.level,
              documentProperty: data.type,
              v3: data.version.slice(0, 1),
              v4: data.version.slice(1),
              documentVersion: data.version,
              sourceInfo: ''
            }
            const newTemp = this.ruleForms.temp || []
            newTemp[index] = newObj
            this.ruleForms.temp = Array.from(newTemp)
          })
        } else {
          this.ruleForms.temp[index].documentCode = ''
        }
      }, 1000 * Math.random())
    }
  }
}
</script>

<style   scoped>
.my-but {
  font-size: 20px;
}
.form-select {
  display: flex;
}

.form-select >>> .el-form-item__content {
  display: flex;
}
</style>
